<div class="febs-container" id="febs-dept" >
    <div class="febs-body layui-fluid" lay-title="机构管理">
        <div class="febs-full layui-row layui-col-space15" style="margin: 0px -7.5px;">
            <div class="layui-col-md7 layui-col-sm12 layui-col-xs12 febs-full" style="padding: 0px 7.5px;">
                <div class="layui-card febs-full">
                    <form class="layui-form layui-table-form" lay-filter="dept-table-form" id="dept-table-form">
                        <div class="layui-row" style="padding: 15px;">
                            <div class="layui-col-md12 layui-col-sm12 layui-col-xs12">
                                <div class="layui-form-item">
                                    <div class="layui-inline"  th:classappend="${hasHeadCompanyRole } ? '' : 'febs-hide'">
                                        <label class="layui-form-label layui-form-label-sm" style="width: auto !important;">公司名称</label>
                                        <div class="layui-input-block" style="width: 280px;margin-left: 90px;">
                                            <select name="tenantSelect" id="tenantSelect">
                                                <option th:each="tenant:${tenantList}" th:value="${tenant.tenantId}"
                                                        th:text="${tenant.tenantName}"></option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label layui-form-label-sm"
                                               style="width: auto !important;">机构名称</label>
                                        <div class="layui-input-block" style="margin-left: 90px;">
                                            <input type="text" name="deptName" autocomplete="off" class="layui-input">
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <div class="layui-btn layui-btn-primary table-action" id="query" style="margin-left: 10px;">
                                            <em class="layui-icon">&#xe848;</em>
                                        </div>
                                        <div class="layui-btn layui-btn-primary table-action" id="reset">
                                            <em class="layui-icon">&#xe79b;</em>
                                        </div>
                                        <div class="layui-btn layui-btn-primary table-action action-more"
                                             shiro:hasAnyPermissions="dept:add,dept:delete,dept:export">
                                            <em class="layui-icon">&#xe875;</em>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                    <div class="dept-tree" lay-filter="deptMainTree" style="margin-left: 1rem"></div>
                </div>
            </div>
            <div class="layui-col-md5 layui-col-sm12 layui-col-xs12 febs-full" style="padding: 0px 7.5px;">
                <div class="layui-card febs-full">
                    <div class="layui-card-header" id="form-header">新增机构</div>
                    <div class="layui-card-body febs-table-full">
                        <form class="layui-form layui-table-form" action="" lay-filter="dept-form">
                            <div class="layui-row">
                                <div class="layui-col-md12">
                                    <div class="layui-form-item febs-hide">
                                        <label class="layui-form-label febs-form-item-require">ID：</label>
                                        <div class="layui-input-block">
                                            <input type="text" name="deptId" class="layui-input">
                                        </div>
                                    </div>
                                    <div class="layui-form-item febs-hide">
                                        <label class="layui-form-label">上级ID：</label>
                                        <div class="layui-input-block">
                                            <input type="text" value="" name="parentId" readonly autocomplete="off"
                                                   class="layui-input">
                                        </div>
                                    </div>
                                    <div class="layui-form-item febs-hide parentName">
                                        <label class="layui-form-label febs-form-item-require">上级机构：</label>
                                        <div class="layui-input-block">
                                            <input type="text" value="" name="parentName" readonly autocomplete="off"
                                                   class="layui-input">
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label febs-form-item-require">机构名称：</label>
                                        <div class="layui-input-block">
                                            <input type="text" name="deptName" autocomplete="off" class="layui-input" minlength="2"
                                                   maxlength="100" lay-verify="required" placeholder="请输入机构名称">
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label febs-form-item-require">机构编号：</label>
                                        <div class="layui-input-block">
                                            <input type="text" name="deptCode" autocomplete="off" class="layui-input"
                                                   minlength="2" maxlength="100" lay-verify="required" placeholder="请输入机构编号">
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-col-md12">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label febs-form-item-require">机构类型：</label>
                                        <div class="layui-input-block">
                                            <input type="radio" name="deptType" title="本部" value="1" checked>
                                            <input type="radio" name="deptType" title="部门" value="2">
                                            <input type="radio" name="deptType" title="科室" value="3">
                                            <input type="radio" name="deptType" title="职场" value="4">
                                            <input type="radio" name="deptType" title="班组" value="5">
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-col-md12">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label febs-form-item-require">业务编码：</label>
                                        <div class="layui-input-block">
                                            <input type="text" name="businessCode" autocomplete="off" class="layui-input" minlength="2"
                                                   maxlength="2" placeholder="请输业务编码，该值影响业务模块编号生成格式" lay-verify="required">
                                        </div>
                                    </div>
                                </div>

                                <div class="layui-col-md12">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">机构排序：</label>
                                        <div class="layui-input-block">
                                            <input type="number" name="orderNum" autocomplete="off" value="1" class="layui-input"
                                                   lay-verify="number" placeholder="请输入输入排序">
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-col-md12">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">机构状态：</label>
                                        <div class="layui-input-block">
                                            <input type="checkbox" id="status-checkbox" name="status" lay-skin="switch" checked lay-text="启用|禁用"
                                                   lay-filter="status">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-form-item" style="text-align: center;">
                                <button type="reset" class="layui-btn febs-hide" id="reset-form"></button>
                                <button class="layui-btn" lay-submit="" lay-filter="dept-form-submit"
                                        id="submit-form">保存</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script data-th-inline="javascript" type="text/javascript">
    layui.use(['dropdown', 'jquery', 'validate', 'febs', 'commonJS', 'form', 'eleTree'], function () {
        var $ = layui.jquery,
            febs = layui.febs,
            form = layui.form,
            commonJS = layui.commonJS,
            validate = layui.validate,
            eleTree = layui.eleTree,
            dropdown = layui.dropdown,
            $view = $('#febs-dept'),
            $query = $view.find('#query'),
            $reset = $view.find('#reset'),
            $header = $view.find('#form-header'),
            $searchForm = $view.find('#dept-table-form'),
            $status = $view.find('#status-checkbox'),
            $deptName = $searchForm.find('input[name="deptName"]'),
            $tenantSelect = $searchForm.find('select[name="tenantSelect"]'),
            currentTenantId = [[${currentTenantId}]],
            _currentDeptData,
            _deptTree;
        form.verify(validate);
        form.render();

        //默认加载当前用户所属公司
        $tenantSelect.val(currentTenantId);
        form.render('select');

        renderDeptTree();
        localStorage.removeItem("selectData")
        eleTree.on("nodeClick(deptMainTree)", function (d) {
            $header.text('修改机构');
            var data = d.data.currentData.data;
            _currentDeptData = data;
            form.val("dept-form", {
                "deptName": data.deptName,
                "deptCode": data.deptCode,
                "businessCode": data.businessCode,
                "orderNum": data.orderNum,
                "deptLeaderId": data.deptLeaderId,
                "deptLeaderName": data.deptLeaderName,
                "deptType": data.deptType,
                "createTime": data.createTime,
                "parentId": data.parentId,
                "tenantId": data.tenantId,
                "deptId": data.deptId,
                "status": data.status =='0'?false:true
            });
        });

        //拖拽回调
        eleTree.on('nodeDrag(deptMainTree)',function (data){
            let currentDept = data.current.data.currentData.data
            let parentDept = data.target.data.currentData.data
            if(currentDept && parentDept){
                var data = currentDept;
                data.parentId = parentDept.deptId
                form.val("dept-form", {
                    "deptName": data.deptName,
                    "deptCode": data.deptCode,
                    "businessCode": data.businessCode,
                    "orderNum": data.orderNum,
                    "deptLeaderId": data.deptLeaderId,
                    "deptLeaderName": data.deptLeaderName,
                    "deptType": data.deptType,
                    "createTime": data.createTime,
                    "parentId": data.parentId,
                    "tenantId": data.tenantId,
                    "deptId": data.deptId,
                    "status": data.status =='0'?false:true
                });
            }
        })

        dropdown.render({
            elem: $view.find('.action-more'),
            click: function (obj, elem, event) {
                if (obj.name === 'add') {
                    reset();
                    var selected = _deptTree.getChecked(false, true);
                    if (selected.length > 1) {
                        febs.alert.warn('只能勾选一个节点作为父级！');
                        return false;
                    }

                    if(selected[0].id && selected[0].name){
                        form.val("dept-form", {
                            "parentId": selected[0] ? selected[0].id : '',
                            'parentName': selected[0] ? selected[0].name : ''
                        });
                        $view.find(".parentName").show()
                    }else{
                        $view.find(".parentName").hide()
                    }

                }
                if (obj.name === 'delete') {
                    var checked = _deptTree.getChecked(false, true);
                    if (checked.length < 1) {
                        febs.alert.warn('请勾选需要删除的机构');
                        return false;
                    }
                    var deptIds = [];
                    layui.each(checked, function (key, item) {
                        deptIds.push(item.id)
                    });
                    febs.modal.confirm('提示', '当您点击确定按钮后，这些记录将会被删除！', function () {
                        febs.get(ctx + 'dept/delete/' + deptIds.join(','), null, function () {
                            febs.alert.success('删除成功！');
                            reloadDeptTree();
                            reset();
                        })
                    });
                }
                if (obj.name === 'export') {
                    febs.download(ctx + 'dept/excel', getQueryParams(), '机构信息表.xls');
                }
            },
            data: [{
                name: 'add',
                title: '新增机构',
                perms: 'dept:add'
            }, {
                name: 'delete',
                title: '删除机构',
                perms: 'dept:delete'
            }, {
                name: 'export',
                title: '导出Excel',
                perms: 'dept:export'
            }]

        });

        $reset.on('click', function () {
            $deptName.val('');
            $tenantSelect.val(currentTenantId);
            form.render('select');
            reloadDeptTree();
            reset();
        });

        $query.on('click', function () {
            reloadDeptTree();
            reset();
        });

        function getQueryParams() {
            return {
                "deptName": $deptName.val()?.trim(),
                "tenantId": $tenantSelect.val(),
            }
        }

        function reset() {
            $view.find(".parentName").hide()
            $header.text('新增机构');
            $view.find('#reset-form').trigger('click');
        }

        function renderDeptTree(selKey) {
            _deptTree = eleTree.render({
                elem: $view.find('.dept-tree'),
                url: ctx + 'dept/tree',
                accordion: false,
                highlightCurrent: true,
                showCheckbox: true,
                checkStrictly: true,
                renderAfterExpand: false,
                expandOnClickNode: false,// 是否在点击节点的时候展开或者收缩节点， 默认值为 true，如果为 false，则只有点箭头图标的时候才会展开或者收缩节点。
                checkOnClickNode: false,
                spread: true,
                draggable:true,//是否开启拖拽功能
                defaultExpandAll:true,
                searchNodeMethod: function (value, data) {
                    if (!value) return true;
                    return data.name.indexOf(value) !== -1;
                },
                where: {
                    "deptName": $deptName.val()?.trim(),
                    "tenantId": $tenantSelect.val(),
                    "invalidate_ie_cache": new Date()
                },
                request: {
                    name: 'name',
                    key: "id",
                    checked: "checked",
                    data: 'data'
                },
                response: {
                    statusName: "code",
                    statusCode: 200,
                    dataName: "data"
                },
                done: function (res) {
                    if (!!selKey) {
                        _deptTree.expandNode(selKey);
                    }
                }
            });
            return _deptTree;
        }

        function reloadDeptTree(key) {
            _deptTree = renderDeptTree(key);
        }

        form.on('submit(dept-form-submit)', function (data) {
            data.field.status = $status.is(':checked')?'1':'0';



            if (data.field.deptId && $header.text().indexOf('修改') !== -1) {
                if (febs.nativeEqual(data.field, _currentDeptData)) {
                    febs.alert.warn('数据未作任何修改！');
                    return false;
                }
                febs.modal.confirm('保存提示', '是否更新机构信息？', function () {
                    febs.post(ctx + 'dept/update', data.field, function () {
                        febs.alert.success('修改成功');
                        reloadDeptTree(data.field.parentId);
                        reset();
                    })
                });
            } else {
                //创建tenantSelect公司下的部门
                if(data.field.tenantId==null || data.field.tenantId ==''){
                    data.field.tenantId = $tenantSelect.val();
                }
                febs.modal.confirm('保存提示', '是否保存机构信息？', function () {
                    febs.post(ctx + 'dept', data.field, function () {
                        febs.alert.success('新增成功');
                        reloadDeptTree(data.field.parentId);
                        reset();
                    })
                });

            }
            return false;
        });

    });
</script>
<style>
    #febs-dept{
        .layui-input-block {
            margin-left: 120px;
        }
    }

</style>